package util;

import Main.Main;
import component.ConsolePane;
import component.VerticalSplitPane;
import ui.HomePage;

import javax.swing.*;
import java.io.*;

/**
 * @author zhongwen
 * @description 编译运行相关的工具
 * @date 2021-12-24 21:14
 */
public class RunUtils {

    public static void setEnvironment(File file) {
        try {
            Process process = Runtime.getRuntime().exec("cmd /c set JAVA_HOME=" + file.getAbsolutePath() +
                    " && set CLASSPATH=%JAVA_HOME%/lib && set Path=%JAVA_HOME%/bin" + " && java");
            InputStream inputStream = process.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "gbk"));
            String s;
            while ((s = reader.readLine()) != null) {
                System.out.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过测试javac命令和java命令判断JDK路径是否选择正确
     */
    public static void testJava(VerticalSplitPane vsp) {
        vsp.showDownPanel();
        JTextArea showArea = null;
        String[] enviroms = {"CLASSPATH=" + Main.configurationBean.getJdkPath().getAbsolutePath() + "/lib/tool.jar;"
                + Main.configurationBean.getJdkPath().getAbsolutePath() + "/lib.dt.jar;" + Main.configurationBean.getNowPath(),
                "Path=" + Main.configurationBean.getJdkPath() + "/bin"};
        if (vsp.getDownPanel() instanceof ConsolePane) {
            ConsolePane panel = (ConsolePane) vsp.getDownPanel();
            showArea = panel.getjTextArea();
            showArea.setText("");
            showArea.append("测试javac命令\n");
            try {
                Process p1 = Runtime.getRuntime().exec("cmd /c javac", enviroms, new File(Main.configurationBean.getNowPath()));
                InputStream errorStream = p1.getErrorStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream, "gbk"));
                String s;
                while ((s = reader.readLine()) != null) {
                    showArea.append(s + "\n");
                }
            } catch (IOException  e) {
                e.printStackTrace();
            }
            showArea.append("测试java命令\n");
            try {
                Process p1 = Runtime.getRuntime().exec("cmd /c java", enviroms, new File(Main.configurationBean.getNowPath()));
                p1.waitFor();
                InputStream errorStream = p1.getErrorStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream, "gbk"));
                String s;
                while ((s = reader.readLine()) != null) {
                    showArea.append(s + "\n");
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
            showArea.requestFocus();
        }
    }

    /**
     * 通过javac编译选中的Java文件
     */
    public static void compileJava(File selectedFile, VerticalSplitPane vsp) {
        if(selectedFile == null){
            JOptionPane.showMessageDialog(HomePage.jf,"请选择文件！","提醒",JOptionPane.PLAIN_MESSAGE, null);
            return;
        }
        String[] enviroms = {"CLASSPATH=" + Main.configurationBean.getJdkPath().getAbsolutePath() + "/lib/tool.jar;"
                + Main.configurationBean.getJdkPath().getAbsolutePath() + "/lib.dt.jar;" + Main.configurationBean.getNowPath(),
                "Path=" + Main.configurationBean.getJdkPath() + "/bin"};
        JTextArea showArea;
        if (vsp.getDownPanel() instanceof ConsolePane) {
            ConsolePane panel = (ConsolePane) vsp.getDownPanel();
            showArea = panel.getjTextArea();
            showArea.setText("");
            vsp.showDownPanel();
            try {
                boolean flag = false;
                Process p1 = Runtime.getRuntime().exec("cmd /c javac -encoding " + FileUtils.getFileEncode(selectedFile) +
                        " " + selectedFile.getAbsolutePath(), enviroms, new File(Main.configurationBean.getNowPath()));
                System.out.println(selectedFile.getAbsolutePath());
                InputStream errorStream = p1.getErrorStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream, "gbk"));
                String s;
                while ((s = reader.readLine()) != null) {
                    flag = true;
                    showArea.append(s + "\n");
                }
                if(!flag){
                    showArea.append("编译成功！\n");
                }
            } catch (IOException  e) {
                e.printStackTrace();
            }
            showArea.requestFocus();
        }
    }
    /**
     * 通过指定的javac命令编译选中的Java文件
     */
    public static void compileJava(File selectedFile, String javacCmd, VerticalSplitPane vsp) {
        if(selectedFile == null){
            JOptionPane.showMessageDialog(HomePage.jf,"请选择文件！","提醒",JOptionPane.PLAIN_MESSAGE, null);
            return;
        }
        String[] enviroms = {"CLASSPATH=" + Main.configurationBean.getJdkPath().getAbsolutePath() + "/lib/tool.jar;"
                + Main.configurationBean.getJdkPath().getAbsolutePath() + "/lib.dt.jar;" + Main.configurationBean.getNowPath(),
                "Path=" + Main.configurationBean.getJdkPath() + "/bin"};
        JTextArea showArea;
        if (vsp.getDownPanel() instanceof ConsolePane) {
            ConsolePane panel = (ConsolePane) vsp.getDownPanel();
            showArea = panel.getjTextArea();
            showArea.setText("");
            vsp.showDownPanel();
            showArea.append("编译命令为：" + javacCmd + "\n");
            try {
                boolean flag = false;
                Process p1 = Runtime.getRuntime().exec("cmd /c " + javacCmd, enviroms, new File(selectedFile.getParent()));
                InputStream errorStream = p1.getErrorStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream, "gbk"));
                String s;
                while ((s = reader.readLine()) != null) {
                    flag = true;
                    showArea.append(s + "\n");
                }
                if(!flag){
                    showArea.append("编译成功！\n");
                }
            } catch (IOException  e) {
                e.printStackTrace();
            }
            showArea.requestFocus();
        }
    }
    /**
     * 通过java运行选中的Java文件
     */
    public static void runJava(File selectedFile, VerticalSplitPane vsp){
        if(selectedFile == null){
            JOptionPane.showMessageDialog(HomePage.jf,"请选择文件！","提醒",JOptionPane.PLAIN_MESSAGE, null);
            return;
        }
        String[] enviroms = {"CLASSPATH=" + Main.configurationBean.getJdkPath().getAbsolutePath() + "/lib/tool.jar;"
                + Main.configurationBean.getJdkPath().getAbsolutePath() + "/lib.dt.jar;" + Main.configurationBean.getNowPath() + ";" + selectedFile.getParent(),
                "Path=" + Main.configurationBean.getJdkPath() + "/bin"};
        JTextArea showArea = null;
        System.out.println(enviroms[0]);
        if(vsp.getDownPanel() instanceof ConsolePane){
            ConsolePane panel = (ConsolePane) vsp.getDownPanel();
            showArea = panel.getjTextArea();
            showArea.setText("");
            vsp.showDownPanel();
            showArea.append(Main.configurationBean.getJdkPath() + "\\bin\\java.exe\n\n");
            showArea.setCaretPosition(showArea.getText().length());
            try {
                // name是带文件后缀名的
                String name = selectedFile.getName();
                int index = name.lastIndexOf(".java");
                System.out.println("java " + name.substring(0, index));
                Process p1 = Runtime.getRuntime().exec("java " + name.substring(0, index), enviroms, new File(selectedFile.getParent()));
                ProcessExecutor per = new ProcessExecutor(p1);
                per.execute(showArea);
                /*InputStream inputStream = p1.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "gbk"));
                String s;
                while ((s = reader.readLine()) != null){
                    showArea.append(s + "\n");
                }*/
                showArea.append("\n\n程序运行结束！\n");
                showArea.setCaretPosition(showArea.getText().length());
            } catch (IOException  e) {
                e.printStackTrace();
            }
            showArea.requestFocus();
        }
    }
    /**
     * 通过指定的java命令运行选中的Java文件
     */
    public static void runJava(File selectedFile, String javaCmd, VerticalSplitPane vsp){
        if(selectedFile == null){
            JOptionPane.showMessageDialog(HomePage.jf,"请选择文件！","提醒",JOptionPane.PLAIN_MESSAGE, null);
            return;
        }
        String[] enviroms = {"CLASSPATH=" + Main.configurationBean.getJdkPath().getAbsolutePath() + "/lib/tool.jar;"
                + Main.configurationBean.getJdkPath().getAbsolutePath() + "/lib.dt.jar;" + Main.configurationBean.getNowPath() + ";" + selectedFile.getParent(),
                "Path=" + Main.configurationBean.getJdkPath() + "/bin"};
        JTextArea showArea = null;
        if(vsp.getDownPanel() instanceof ConsolePane){
            ConsolePane panel = (ConsolePane) vsp.getDownPanel();
            showArea = panel.getjTextArea();
            showArea.setText("");
            vsp.showDownPanel();
            showArea.append(Main.configurationBean.getJdkPath() + "\\bin\\java.exe\n");
            showArea.append("运行命令为：" + javaCmd + "\n\n");
            showArea.setCaretPosition(showArea.getText().length());
            try {
                Process p1 = Runtime.getRuntime().exec("cmd /c " + javaCmd, enviroms, new File(Main.configurationBean.getNowPath()));
                ProcessExecutor per = new ProcessExecutor(p1);
                per.execute(showArea);
                showArea.append("\n\n程序运行结束！\n");
                showArea.setCaretPosition(showArea.getText().length());
            } catch (IOException  e) {
                e.printStackTrace();
            }
            showArea.requestFocus();
        }
    }
    /**
     * 执行任意终端命令
     */
    public static void runCmd(String javaCmd, VerticalSplitPane vsp){
        String[] enviroms = {"CLASSPATH=" + Main.configurationBean.getJdkPath().getAbsolutePath() + "/lib/tool.jar;"
                + Main.configurationBean.getJdkPath().getAbsolutePath() + "/lib.dt.jar;" + Main.configurationBean.getNowPath() ,
                "Path=" + Main.configurationBean.getJdkPath() + "/bin"};
        JTextArea showArea = null;
        if(vsp.getDownPanel() instanceof ConsolePane){
            ConsolePane panel = (ConsolePane) vsp.getDownPanel();
            showArea = panel.getjTextArea();
            showArea.setText("");
            vsp.showDownPanel();
            showArea.append("运行命令为：" + javaCmd + "\n\n");
            showArea.setCaretPosition(showArea.getText().length());
            try {
                Process p1 = Runtime.getRuntime().exec("cmd /c " + javaCmd, enviroms, new File(Main.configurationBean.getNowPath()));
                ProcessExecutor per = new ProcessExecutor(p1);
                per.execute(showArea);
                showArea.append("\n\n程序运行结束！\n");
                showArea.setCaretPosition(showArea.getText().length());
            } catch (IOException  e) {
                e.printStackTrace();
            }
            showArea.requestFocus();
        }
    }
}
